/**
 * 
 */
package org.jim.server.demo.command;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.netty.util.internal.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.jim.core.ImChannelContext;
import org.jim.core.ImConst;
import org.jim.core.ImPacket;
import org.jim.core.exception.ImException;
import org.jim.core.http.HttpRequest;
import org.jim.core.packets.Command;
import org.jim.core.packets.LoginReqBody;
import org.jim.core.utils.JsonKit;
import org.jim.server.JimServerAPI;
import org.jim.server.command.CommandManager;
import org.jim.server.command.handler.LoginReqHandler;
import org.jim.server.demo.entity.ImUserInfo;
import org.jim.server.demo.service.impl.ImUserInfoServiceImpl;
import org.jim.server.processor.handshake.WsHandshakeProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;


/**
 *
 * 需要根据业务处理相关的 cmd 处理器
 *
 * DemoWsHandshakeProcessor 在握手环节处理相关业务
 *
 * @author WChao
 *
 */
@Configuration
public class DemoWsHandshakeProcessor extends WsHandshakeProcessor {

	private static final Logger log = LoggerFactory.getLogger(DemoWsHandshakeProcessor.class);

	@Resource
	private ImUserInfoServiceImpl imUserInfoService;

	/**
	 * 实现握手成功后接口
	 */
	@Override
	public void onAfterHandshake(ImPacket packet, ImChannelContext imChannelContext) throws ImException {

		log.info("握手成功后接口！");

		LoginReqHandler loginHandler = (LoginReqHandler)CommandManager.getCommand(Command.COMMAND_LOGIN_REQ);

		HttpRequest request = (HttpRequest)packet;
		String username = request.getParams().get("username") == null ? null : (String)request.getParams().get("username")[0];
		String password = request.getParams().get("password") == null ? null : (String)request.getParams().get("password")[0];
		String token = request.getParams().get("token") == null ? null : (String)request.getParams().get("token")[0];
		LoginReqBody loginBody = new LoginReqBody(username,password,token);
		/**
		 * 做用户信息鉴权，鉴权不通过则移除该链接
		 */
		if(!checkUserAuth(loginBody)){
			log.info("业务层鉴权失败！");
			JimServerAPI.remove(imChannelContext, "业务层鉴权失败");
		}

		byte[] loginBytes = JsonKit.toJsonBytes(loginBody);
		request.setBody(loginBytes);
		try{
			request.setBodyString(new String(loginBytes, ImConst.CHARSET));
		}catch (Exception e){
			throw new ImException(e);
		}
		ImPacket loginRespPacket = loginHandler.handler(request, imChannelContext);
		if(loginRespPacket != null){
			JimServerAPI.send(imChannelContext, loginRespPacket);
		}
	}

	/**
	 * 对新连接做鉴权操作
	 *
	 * todo: 后续需要根据token 进一步鉴权
	 */
	public Boolean checkUserAuth(LoginReqBody loginReqBody){

		String userId = loginReqBody.getUserId();
		String passWord = loginReqBody.getPassword();

		if(StringUtils.isBlank(userId) || StringUtils.isBlank(passWord)){
			log.info("用户ID 或 密码为空，鉴权失败！");
		}
		QueryWrapper<ImUserInfo> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("user_id",userId);
		ImUserInfo userInfo = imUserInfoService.getOne(queryWrapper);
		if(ObjectUtil.isNull(userInfo)){
			log.info("用户不存在！,鉴权失败！");
			return false;
		}
		if(!userInfo.getPassWord().equals(passWord)){
			log.info("用户密码错误！,鉴权失败！");
			return false;
		}

		return true;
	}
}
